import 'package:boss/color_constant.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';

class LongTextFormField extends StatefulWidget {
  final ValueChanged<String> onChanged;
  final String hintText;
  final int maxLength;
  final int maxLines;
  final String initValue;

  const LongTextFormField({
    Key key,
    this.onChanged,
    this.hintText,
    this.maxLength,
    this.maxLines,
    this.initValue,
  }) : super(key: key);

  @override
  _LongTextFormFieldState createState() => _LongTextFormFieldState();
}

class _LongTextFormFieldState extends State<LongTextFormField> {
  final OutlineInputBorder border = OutlineInputBorder(
    borderSide: BorderSide(
      color: ColorConstant.e6e6,
      width: 1.px,
    ),
    borderRadius: BorderRadius.circular(
      10.w,
    ),
  );

  TextEditingController _controller;

  int get _textLength => _controller.text.length;

  @override
  void initState() {
    super.initState();

    _controller = TextEditingController(text: widget.initValue);

    _controller.addListener(_eventHandle);
  }

  @override
  void dispose() {
    _controller.removeListener(_eventHandle);
    _controller.dispose();
    _controller = null;
    super.dispose();
  }

  _eventHandle() {
    if (_textLength > widget.maxLength) {
      _controller.text = _controller.text.substring(0, widget.maxLength);
      _controller.selection = TextSelection.collapsed(offset: _textLength);
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        TextFormField(
          keyboardAppearance: Brightness.light,
          controller: _controller,
          decoration: InputDecoration(
            border: border,
            enabledBorder: border,
            focusedBorder: border,
            hintText: widget.hintText,
            hintStyle: TextStyleConstant().normal_4_26,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 20.w,
              vertical: 20.w,
            ),
          ),
          style: TextStyleConstant().normal_1_26,
          maxLines: widget.maxLines,
          onChanged: widget.onChanged,
        ),
        Positioned(
          bottom: 20.w,
          right: 20.w,
          child: Text(
            '$_textLength/${widget.maxLength}',
            style: TextStyleConstant().normal_4_22,
          ),
        ),
      ],
    );
  }
}
